<template>
  <div ref="mapContainer" class="baidu-map-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, defineProps, defineEmits } from 'vue'

// 导入本地小图标 - 确保图片路径正确
import markerIcon from '@/assets/images/car.png'

const props = defineProps({
  // 初始经纬度
  lng: {
    type: Number,
    default: 113.404
  },
  lat: {
    type: Number,
    default: 32.915
  },
  // 缩放级别
  zoom: {
    type: Number,
    default: 18
  },
  // 图标显示尺寸
  iconSize: {
    type: Array,
    default: () => [32, 32]
  }
})

const emit = defineEmits(['marker-click', 'map-loaded'])

const mapContainer = ref(null)
const map = ref(null)
const marker = ref(null)

// 初始化地图
const initMap = () => {
  map.value = new BMap.Map(mapContainer.value)
  const point = new BMap.Point(props.lng, props.lat)
  map.value.centerAndZoom(point, props.zoom)
  
  // 添加基本控件
  map.value.addControl(new BMap.NavigationControl())
  map.value.enableScrollWheelZoom()
  
  // 添加优化后的标记
  addMarker(point)
  
  emit('map-loaded', map.value)
}

// 优化的小图标标记
const addMarker = (point) => {
  if (marker.value) {
    map.value.removeOverlay(marker.value)
  }
  
  // 关键配置 - 小尺寸图标
  const icon = new BMap.Icon(
    markerIcon,
    new BMap.Size(...props.iconSize),
    {
      offset: new BMap.Size(props.iconSize[0]/2, props.iconSize[1]), // 水平居中，垂直底部对齐
      imageOffset: new BMap.Size(0, 0),
      imageSize: new BMap.Size(...props.iconSize) // 必须与显示尺寸一致
    }
  )
  
  marker.value = new BMap.Marker(point, { icon })
  map.value.addOverlay(marker.value)
  
  // 点击事件
  marker.value.addEventListener('click', () => {
    emit('marker-click', {
      lng: point.lng,
      lat: point.lat
    })
    
    // 显示信息窗口
    const infoWindow = new BMap.InfoWindow(`
      <div style="padding: 8px; min-width: 120px;">
        <div>经度: ${point.lng.toFixed(6)}</div>
        <div>纬度: ${point.lat.toFixed(6)}</div>
      </div>
    `)
    map.value.openInfoWindow(infoWindow, point)
  })
}

// 监听坐标变化
watch(() => [props.lng, props.lat], ([newLng, newLat]) => {
  if (map.value) {
    const newPoint = new BMap.Point(newLng, newLat)
    map.value.panTo(newPoint)
    addMarker(newPoint)
  }
})

onMounted(() => {
  if (typeof BMap !== 'undefined') {
    initMap()
  } else {
    console.error('百度地图API未加载')
  }
})
</script>

<style scoped>
.baidu-map-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
  background-color: #f5f5f5;
}
</style>